package com.study.factory;

import com.study.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;

/**
 * @author Qi XueSong
 */
@Component("proxyFactory")
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;

    /**
     * 生成动态代理
     * @param obj 委托对象
     * @param <T> 代理对象
     */
    public <T> T getJdkProxy(Object obj){
        Object o = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), (proxy, method, args) -> {
            Object result;
            try {
                // 开启事务
                transactionManager.beginTransaction();
                // 调用原对象方法
                result = method.invoke(obj, args);
                // 提交事务
                transactionManager.commitTransaction();
            } catch (Exception e) {
                // 回滚事务
                transactionManager.rollbackTransaction();
                e.printStackTrace();
                // 抛出异常便于上层servlet捕获
                throw e;

            }
            return result;
        });
        return (T) o;
    }
}
